import cube from "@/views/datasource/api/cube.js"
import { Message } from "@arco-design/web-vue"

export const dimension = ref([])
// 数据集
export const cubeLoading = ref(false)
export const cubeList = ref([])
//全部字段
let oldAllFields = []
export const columns = [
  {
    title: "数据集名称",
    field: "name"
  },
  {
    title: "数据源",
    field: "datasource.name"
  },
  {
    title: "创建人",
    field: "user.name"
  },
  {
    title: "创建时间",
    field: "create_time"
  },
  {
    title: "更新时间",
    field: "update_time"
  },
  {
    title: "操作",
    width: 250,
    slots: { default: "action" }
  }
]
export const getCubeList = (params) => {
  cubeLoading.value = true
  params.saiType = "all"
  cube.getPageList(params).then((res) => {
    cubeList.value = res.data
    cubeLoading.value = false
  })
}
export const cubeDetail = ref({})
export const getDataCubeDetail = async (id) => {
  const res = await cube.read(id)
  cubeDetail.value = res.data
  cubeLoading.value = false
  setTimeout(() => {
    oldAllFields = JSON.parse(JSON.stringify(dimension.value))
  }, 2000)
}
// 数据列表
export const cubeDataList = ref({
  column: [],
  data: [],
  total: 0
})
// 预览数据
export const previewData = (data) => {
  cubeLoading.value = true
  dataCubePreview(data).then((res) => {
    cubeDataList.value = res.data
    cubeLoading.value = false
  })
}
// 搜索
export const searchAllFields = (keyword) => {
  const filterVal = String(keyword).trim().toLowerCase()
  if (filterVal) {
    const filterRE = new RegExp(filterVal, "gi")
    const searchProps = ["title", "field"]
    const rest = oldAllFields.filter((item) =>
      searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterVal) > -1)
    )
    const all = rest.map((row) => {
      const item = Object.assign({}, row)
      searchProps.forEach((key) => {
        item[key] = String(item[key]).replace(filterRE, (match) => `${match}`)
      })
      return item
    })
    dimension.value = g.Copy(all)
  } else {
    dimension.value = g.Copy(oldAllFields)
  }
}
// 枚举
export const enumList = ref([])
export const getEnumList = async (currentComponent, field, code = "") => {
  // 获取加载状态
  Message.loading("加载中...")
  enumList.value = []
  const params = {
    datasource_id: currentComponent.datasource_id,
    cube_id: currentComponent.cube_id,
    field,
    code
  }
  const res = await cube.dataCubeEnum(params)
  enumList.value = res.data
}
